package com.gxa.hualian.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "CORSFilter",urlPatterns = "/*")
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {


}
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
        // 跨域
        String origin = httpServletRequest.getHeader("Origin");
        if (origin == null) {
            httpServletResponse.addHeader("Access-Control-AllowOrigin", "*");
        } else {
            if (httpServletRequest.getMethod().equals("OPTIONS")) {
                httpServletResponse.addHeader("Access-ControlAllow-Origin", origin);
            }
            httpServletResponse.addHeader("Access-Control-AllowOrigin", origin);
        }
        httpServletResponse.addHeader("Access-Control-AllowHeaders",
                "Origin, x-requested-with, Content-Type, Accept,XCookie");
        httpServletResponse.addHeader("Access-Control-AllowCredentials", "true");
        httpServletResponse.addHeader("Access-Control-AllowMethods", "GET,POST,PUT,OPTIONS,DELETE");
        if (httpServletRequest.getMethod().equals("OPTIONS")) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
    }

